package com.hxrfid.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxrfid.common.core.domain.PageQuery;
import com.hxrfid.common.core.page.TableDataInfo;
import com.hxrfid.common.helper.LoginHelper;
import com.hxrfid.common.utils.StringUtils;
import com.hxrfid.project.domain.BsSearch;
import com.hxrfid.project.domain.bo.BsSearchBo;
import com.hxrfid.project.domain.vo.BsSearchVo;
import com.hxrfid.project.mapper.BsSearchMapper;
import com.hxrfid.project.service.IBsSearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 搜索历史Service业务层处理
 *
 * @author hxrfid
 * @date 2025-06-12
 */
@RequiredArgsConstructor
@Service
public class BsSearchServiceImpl extends ServiceImpl<BsSearchMapper, BsSearch> implements IBsSearchService {

    private final BsSearchMapper baseMapper;

    /**
     * 查询搜索历史
     * @param id 主键ID
     * @return 搜索历史
     */
    @Override
    public BsSearchVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询搜索历史列表
     * @param bo 搜索历史对象
     * @param pageQuery 主键ID
     * @return 搜索历史列表
     */
    @Override
    public TableDataInfo<BsSearchVo> queryPageList(BsSearchBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BsSearch> lqw = buildQueryWrapper(bo);
        Page<BsSearchVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询搜索历史列表
     * @param bo 搜索历史对象
     * @return 搜索历史列表
     */
    @Override
    public List<BsSearchVo> queryList(BsSearchBo bo) {
        LambdaQueryWrapper<BsSearch> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
    * 组装查询条件
    * @param bo 搜索历史对象
    * @return 查询条件
    */
    private LambdaQueryWrapper<BsSearch> buildQueryWrapper(BsSearchBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BsSearch> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), BsSearch::getContent, bo.getContent());
        lqw.eq(bo.getCount() != null, BsSearch::getCount, bo.getCount());
        lqw.eq(bo.getUserId() != null, BsSearch::getUserId, bo.getUserId());
        lqw.orderByDesc(BsSearch::getCount);
        return lqw;
    }

    /**
     * 新增搜索历史
     * @param bo 搜索历史对象
     * @return 是否成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean insertByBo(BsSearchBo bo) {
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        BsSearch add = BeanUtil.toBean(bo, BsSearch.class);
        validEntityBeforeSave(add);
        // 已经搜索过的记录：搜索此处加1
        if (ObjectUtil.isNotNull(add.getId())) {
            add.setCount(add.getCount() + 1);
            baseMapper.updateById(add);
        } else { // 新增搜索记录
            baseMapper.insert(add);
        }
        return true;
    }

    /**
     * 修改搜索历史
     * @param bo 搜索历史对象
     * @return 是否成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean updateByBo(BsSearchBo bo) {
        BsSearch update = BeanUtil.toBean(bo, BsSearch.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     * @param entity 搜索历史对象
     */
    private void validEntityBeforeSave(BsSearch entity){
        // 查询搜索记录是否已存在
        entity = baseMapper.selectOne(Wrappers.<BsSearch>lambdaQuery()
            .eq(BsSearch::getContent, entity.getContent())
            .eq(BsSearch::getUserId, entity.getUserId()));
    }

    /**
     * 批量删除搜索历史
     * @param ids 主键ID的list
     * @param isValid 是否业务校验
     * @return 是否成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
